package com.itheima.bos.web.action.take_delivery;

import java.util.HashMap;
import java.util.Map;


import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;

import com.itheima.bos.domain.take_delivery.WayBill;
import com.itheima.bos.service.take_delivery.WayBillService;
import com.itheima.bos.web.common.action.BaseAction;
import com.opensymphony.xwork2.ActionContext;

@ParentPackage("json-default")
@Namespace("/")
@Scope("prototype")
@Controller
public class WayBillAction extends BaseAction<WayBill> {
	
	private static final Logger LOGGER = Logger.getLogger(WayBillAction.class);
	@Autowired
	private WayBillService wayBillService;
	
	@Action(value="waybill_save",results={@Result(name="success",type="json")})
	public String save(){
		Map<String,Object> map = new HashMap<String,Object>();
		try{
			if (model.getOrder() != null
					&& (model.getOrder().getId() == null || model.getOrder()
							.getId() == 0)) {
				model.setOrder(null);
			}
			wayBillService.save(model);
			map.put("success", true);
			map.put("msg", "保存运单成功！");
		LOGGER.info("保存运单成功，运单号："+ model.getWayBillNum());
		} catch(Exception e){
			e.printStackTrace();
			map.put("success", false);
			map.put("msg", "保存运单失败！");
			LOGGER.info("保存运单失败，运单号："+ model.getWayBillNum(),e);
		}
		ActionContext.getContext().getValueStack().push(map);
		return SUCCESS;	
	}
	
	@Action(value="waybill_pageQuery",results={@Result(name="success",type="json")})
	public String pageQuery(){
		
		Pageable pageable = new PageRequest(page-1, rows,new Sort(
				new Sort.Order(Sort.Direction.DESC,"id")));
		Page<WayBill> pagedata = wayBillService.findPageData(model,pageable);
		pushPageDataToValueStack(pagedata);
		return SUCCESS;		
	}
	
	@Action(value="waybill_findByWayBillNum",results={@Result(name="success",type="json")})
	public String findByWayBillNum(){
		
		WayBill wayBill=wayBillService.findByWayBillNum(model.getWayBillNum());	
		System.out.println(wayBill);
		Map<String,Object> map = new HashMap<String,Object>();
		if (wayBill==null) {
			map.put("success", false);
		} else {
			map.put("success", true);
			map.put("wayBillData",wayBill);
		}
		ActionContext.getContext().getValueStack().push(map);
		return SUCCESS;	
	}
}
